package ssh

import (
	"fmt"
	"github.com/pkg/sftp"
	log "github.com/sirupsen/logrus"
	"golang.org/x/crypto/ssh"
)

type SSHClient struct {
	username   string
	password   string
	address    string
	config     *ssh.ClientConfig
	Client     *ssh.Client
	Session    *ssh.Session
	SftpClient *sftp.Client
	LastResult string
}

func (c *SSHClient) Init(user, pwd, addr string) {
	c.username = user
	c.password = pwd
	c.address = addr
}

func (c *SSHClient) Connect() (*SSHClient, error) {
	//sshInfo := getSSHInfo()
	//c.config = sshInfo.SSHConfig
	//c.address = sshInfo.HostAddress
	//c.username = sshInfo.Username
	//c.password = sshInfo.Password
	c.config = &ssh.ClientConfig{
		User: c.username,
		Auth: []ssh.AuthMethod{
			ssh.Password(c.password),
		},
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
	}
	client, err := ssh.Dial("tcp", c.address, c.config)
	if err != nil {
		return nil, err
	}
	c.Client = client
	return c, nil
}

func (c *SSHClient) NewSession() error {
	session, err := c.Client.NewSession()
	if err != nil {
		return err
	}
	c.Session = session
	return nil
}

func (c *SSHClient) NewSftpClient() error {
	sftpClient, err := sftp.NewClient(c.Client)
	if err != nil {
		return fmt.Errorf("Failed to init sftp client: %s", err.Error())
	}
	c.SftpClient = sftpClient
	return nil
}

func (c *SSHClient) Close() {
	err := c.SftpClient.Close()
	if err != nil {
		log.Errorf("Close sftp clinet error : %s ", err.Error())
	}
	err = c.Session.Close()
	if err != nil {
		log.Errorf("Close ssh session error : %s ", err.Error())
	}
	err = c.Client.Close()
	if err != nil {
		log.Errorf("Close ssh client error : %s ", err.Error())
	}
}
